package com.yfp.client.generator;

import com.yfp.client.domain.Client;
import com.yfp.common.core.exception.InnerAuthException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: Token鉴权
 * 
 * @CreateDate: 2024/5/16 9:23
 * @UpdateUser: 
 * @UpdateDate: 2024/5/16 9:23
 * @UpdateRemark: 暂无修改
 * @Version: 1.0
 */
public class TokenGenerator {
    // 私钥
    private static final String SECRET_KEY = "yfp-winiapp-2023";

    /**
     * 生产token
     * @param client 客户对象
     * @return
     */
    public static String createToken(Client client) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        // 添加claims
        Map<String, Object> claims = new HashMap<>();
        claims.put("clientId", client.getId());
        claims.put("mobile", client.getMobile());
        claims.put("openId", client.getOpenId());
        claims.put("cityName", client.getCityName());
        // 生成token
        String token = Jwts.builder()
                .setClaims(claims)
                .setSubject(claims.toString())
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();

        return token;
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean validateToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            return true; // token验证通过
        } catch (Exception e) {
            return false; // token验证失败
        }
    }

    /**
     * 解析JWT
     * @param token
     * @return
     */
    public static Claims parseJWT(String token){
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            throw new InnerAuthException("Authorization无效");
        }
    }
}